home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 13342 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.6 KB

  1. Path: mail2news.demon.co.uk!genesis.demon.co.uk
  2. From: Lawrence Kirby <fred@genesis.demon.co.uk>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: reversing a string
  5. Date: Sun, 07 Apr 96 10:48:36 GMT
  6. Organization: none
  7. Message-ID: <828874116snz@genesis.demon.co.uk>
  8. References: <4k6cjl$j8f@central.server.swt.edu>
  9. Reply-To: fred@genesis.demon.co.uk
  10. X-NNTP-Posting-Host: genesis.demon.co.uk
  11. X-Newsreader: Demon Internet Simple News v1.27
  12. X-Mail2News-Path: genesis.demon.co.uk
  13.  
  14. In article <4k6cjl$j8f@central.server.swt.edu>
  15.            ln16674@nyssa.swt.edu "Leland Newsom" writes:
  16.  
  17. >I have a challenge from a friend of mine.  He wanted me to reverse a string 
  18. >with recursion without using any additional variables or loops.  I got mine
  19. >to work by using exclusive or, but I needed an additional variable.  Can 
  20. >someone help with this problem without using the additional variable?
  21.  
  22. There is a solution although (the one I'm thinking of) won't gain any
  23. prizes for efficiency. I won't give the answer (yet) because this is a
  24. worthwhile problem for getting used to recursion. All you need is a function:
  25.  
  26.  
  27. void reverse(char *str)
  28. {
  29.     ...
  30. }
  31.  
  32. Within that the operations you have available are to swap 2 characters at
  33. the start of the string (you don't know where the end is) using, say, an
  34. exclusive or swap, and to reverse a shorter suffix of the string via a
  35. recursive call. You should aim to get from something like:
  36.  
  37.     a b c d e f g
  38.  
  39. to
  40.  
  41.     g a b c d e f
  42.  
  43. which can then be completed via a call to reverse(str+1)
  44.  
  45. -- 
  46. -----------------------------------------
  47. Lawrence Kirby | fred@genesis.demon.co.uk
  48. Wilts, England | 70734.126@compuserve.com
  49. -----------------------------------------
  50.